//
//  PlayerView.m
//  StroeBode
//
//  Created by Kratos on 14/12/5.
//
//

#import "PlayerView.h"

@interface PlayerView ()
@property (nonatomic , weak) IBOutlet UIButton *statusButton;
@property (nonatomic , weak) IBOutlet UIButton *zoomButton;
@property (nonatomic , weak) IBOutlet UIActivityIndicatorView *moviebuffer;
@property (nonatomic , assign) BOOL isPlaying;//是否在播放
@property (nonatomic , assign) BOOL isAddedKVO;//是否添加了KVO
@property (nonatomic , setter=setAutomataPlayWhenReady:) BOOL automata;//自动播放

@property (nonatomic , strong) NSString *avPath;//播放路径
@property (nonatomic , assign) BOOL isLocalPath;//是否是网路播放路径
@property (nonatomic , assign) BOOL playFiled;//播放失败
@property (nonatomic , assign) BOOL isLoading;//是否正在加载
@end

@implementation PlayerView

-(void)awakeFromNib
{    
    [self setBackgroundColor:[UIColor blackColor]];
    
    AVPlayer *player = [AVPlayer new];
    player.allowsExternalPlayback = NO;
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
    playerLayer.frame = self.layer.bounds;
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self setPlayer:player];
    
    UITapGestureRecognizer *oneTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(oneTapAction:)];
    oneTap.numberOfTapsRequired = 1;
    [self addGestureRecognizer:oneTap];
}


+(Class)layerClass{
    return [AVPlayerLayer class];
}

-(AVPlayer*)player{
    return [(AVPlayerLayer*)[self layer]player];
}

-(void)setPlayer:(AVPlayer *)player{
    [(AVPlayerLayer*)[self layer]setPlayer:player];
}



-(void)setAVUrl:(NSString *)urlstr
{
    [self setPlayPath:urlstr isLocal:NO];
}

-(void)setLocalAVPath:(NSString *)path
{
    [self setPlayPath:path isLocal:YES];
}

-(void)setPlayPath:(NSString *)path isLocal:(BOOL)flag
{
    if (path && path.length > 0) {
        _isLoading = YES;
        _avPath = path;
        _isLocalPath = flag;
        
        NSURL* urlvideo = [NSURL URLWithString:path];
        AVAsset *movieAsset = flag ? [AVAsset assetWithURL:urlvideo] : [AVURLAsset URLAssetWithURL:urlvideo options:nil];
        
        AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
        
        [self.player replaceCurrentItemWithPlayerItem:playerItem];
        
        [self addListener];
        
        [_moviebuffer startAnimating];
        [_moviebuffer setHidden:NO];
        
         [_statusButton setHidden:YES];
    }
}

-(void)addListener
{

    if (_isAddedKVO) {
        return;
    }
    
    //检测视频加载状态，加载完成隐藏风火轮
    [self.player.currentItem addObserver:self
                              forKeyPath:@"status"
                                 options:NSKeyValueObservingOptionNew
                                 context:nil];
    
    [self.player.currentItem  addObserver:self
                               forKeyPath:@"loadedTimeRanges"
                                  options:NSKeyValueObservingOptionNew
                                  context:nil];
    
    //添加视频播放完成的notifation
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(moviePlayDidEnd:)
                                                name:AVPlayerItemDidPlayToEndTimeNotification
                                              object:self.player.currentItem];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationWillResignActive:)
                                                 name:UIApplicationWillResignActiveNotification
                                               object:nil];
    
    _isAddedKVO = YES;
}

-(IBAction)play
{
    //判断是否上次播放失败，并且没有加载
    if (_playFiled && !_isLoading) {
        [self setPlayPath:_avPath isLocal:_isLocalPath];
        return;
    }
    
    [self.player play];
    _isPlaying = YES;
    [_statusButton setHidden:_isPlaying];
}

-(IBAction)pause
{
    [self setAutomataPlayWhenReady:NO];
    [self.player pause];
    _isPlaying = NO;
    [_statusButton setHidden:_isPlaying];
}

-(IBAction)magnifyAVPlayer:(id)sender
{
    if (!_avPath && _avPath.length == 0) {
        return;
    }
    
    [[NSNotificationCenter defaultCenter]postNotificationName:kRFMNotificationAVMagnified
                                                       object:nil
                                                     userInfo:@{@"path":_avPath}];
    
    [self pause];
}


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self];
    NSLog(@"began %f==%f",touchPoint.x,touchPoint.y);
    _x = (touchPoint.x);
    _y = (touchPoint.y);
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesMoved:touches withEvent:event];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesEnded:touches withEvent:event];
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self];
    NSLog(@"end %f==%f",touchPoint.x,touchPoint.y);
    
    if ((touchPoint.x - _x) >= 50 && (touchPoint.y - _y) <= 20 && (touchPoint.y - _y) >= -20){
        NSLog(@"快进");
        
    }else if ((_x - touchPoint.x) >= 50 && (touchPoint.y - _y) <= 20 && (touchPoint.y - _y) >= -20){
        NSLog(@"快退");
        
        
    }else if((touchPoint.y - _y) >= 50 && (touchPoint.x - _x) <= 20 && (touchPoint.x - _x) >= -20){
        NSLog(@"减小音量");
        
    }else if ((_y - touchPoint.y) >= 50 && (touchPoint.x - _x) <= 20 && (touchPoint.x - _x) >= -20){
        NSLog(@"加大音量");
        
    }
}

-(IBAction)oneTapAction:(UITapGestureRecognizer *)recognizer
{
    //判断是否上次播放失败，并且没有加载
    if (_playFiled && !_isLoading) {
        [self setPlayPath:_avPath isLocal:_isLocalPath];
        return;
    }
    
    //正在加载中
    if (_isLoading) {
        return;
    }
    
    _isPlaying = !_isPlaying;
    
    [_statusButton setHidden:_isPlaying];
    
    if (_isPlaying) {
        [self.player play];
    }else{
        [self.player pause];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItem *playerItem = (AVPlayerItem*)object;
        
        //视频加载完成
        _isLoading = NO;
        
        [_moviebuffer stopAnimating];
        [_moviebuffer setHidden:YES];
        
        _isPlaying = NO;
        [_statusButton setHidden:_isPlaying];
        
        _playFiled = NO;
        switch (playerItem.status) {
            case AVPlayerItemStatusReadyToPlay:
            {
                //加载完成是否自动播放
                if (_automata) {
                    [self play];
                }
            }
                break;
            case AVPlayerItemStatusFailed:
            {
                [self removeKVO];
                _playFiled = YES;
            }
                break;
            case AVPlayerItemStatusUnknown:
            {
                [self removeKVO];
                _playFiled = YES;
            }
                break;
                
            default:
                break;
        }
        
    }
    
    if ([keyPath isEqualToString:@"loadedTimeRanges"])
    {
        
    }
    
}

-(void)moviePlayDidEnd:(NSNotification*)notification{
    //视频播放完成
    NSLog(@"播放完成 加入广告");
}

-(void)applicationWillResignActive:(NSNotification *)notification
{
    if (_isPlaying) {
        [self pause];
    }
}

-(void)dealloc
{
    [self removeKVO];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

-(void)removeKVO
{
    _isAddedKVO = NO;
    [self.player.currentItem removeObserver:self forKeyPath:@"status"];
    [self.player.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
}

@end
